#include "tileset.h"
#include <stdio.h>

using namespace std;

Tileset::Tileset(char *name){
    load(name);
}

Tileset::~Tileset(){
    free(mCollData);
}


void Tileset::load(char *name){
    FILE *f = fopen(name,"rb");
    if(f){
        fseek(f,7,SEEK_SET);
        char version;
        char *imgname;
        fread(&version,1,1,f);
        if(version == '1'){
            fread(&mTileW,sizeof(int),1,f);
            fread(&mTileH,sizeof(int),1,f);
            fread(&mTilesPerRow,sizeof(int),1,f);
            fread(&mRows,sizeof(int),1,f);
            
            char length = 0;
            fread(&length,1,1,f);
            mImgName = (char*)malloc(length);
            fread(mImgName,length,1,f);
            
            mSurface = SDL_LoadBMP(mImgName);
            
            mCollData = (unsigned char*)malloc(mTilesPerRow*mRows);
            fread(mCollData,mTilesPerRow*mRows,1,f);
        }
    }
}

void Tileset::save(char *name){
    FILE *f = fopen(name,"wb");
    if(f){
        fwrite("TILESET",7,1,f);
        fwrite(&mTileW,sizeof(int),1,f);
        fwrite(&mTileH,sizeof(int),1,f);
        fwrite(&mTilesPerRow,sizeof(int),1,f);
        fwrite(&mRows,sizeof(int),1,f);
        
        char length = strlen(mImgName)+1;
        fwrite(&length,sizeof(int),1,f);
        fwrite(mImgName,length,1,f);
        fwrite(mCollData,mTilesPerRow*mRows,1,f);
        
        fclose(f);
    }
}
